import { request } from '@@/plugin-request';
import { message } from 'antd';

export type CurdRequestProps = {
  resourceName: string;
}

export function createRequest(props: CurdRequestProps) {
  const deleteRequest = async (id: string) => {
    return await request(`/api/v1/${props.resourceName}/${id}`, { method: 'DELETE' });
  }

  const detailRequest = async (id: string) => {
    const data = await request(`/api/v1/${props.resourceName}/detail`, { method: 'POST', data: { id } });
    if (!data.success) {
      return message.error('数据不存在');
    }
    return data.data;
  }

  const listRequest = async (data: any) => {
    return await request(`/api/v1/${props.resourceName}/list`, {
      method:'POST', data
    });
  }

  const saveRequest = async (value: any) => {
    let resp;
    if (value.id && value.id !== '') {
      resp = await request(`/api/v1/${props.resourceName}/update`, { method: 'PUT', data: value });
    }
    else {
      resp = await request(`/api/v1/${props.resourceName}/insert`, { method: 'POST', data: value });
    }
    return resp;
  }
  return {deleteRequest, detailRequest, listRequest, saveRequest}
}